package com.example.demo.controller;


import com.example.demo.model.Teacher;

import com.example.demo.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @RequestMapping("list")
    public String list(ModelMap modelMap){
        modelMap.put("teacherList",teacherService.list());
        return "teacher/list";
    }

    @RequestMapping("delete/{id}")
    public String delete(@PathVariable Integer id) {
         teacherService.delete(id);
        return "redirect:/teacher/list";
    }

    @RequestMapping("save")
    public String save(Teacher teacher, ModelMap modelMap) {
        try{
            teacherService.save(teacher);
        }
        catch(Exception e){
            e.printStackTrace();
            modelMap.put("error", e);
            return "error";
        }
        return "redirect:/teacher/list";//重定向到list页面
    }

    @RequestMapping("edit/{id}")
    public String edit(@PathVariable  Integer id,ModelMap modelMap){
        modelMap.put("teacher", teacherService.get(id));
        return "teacher/edit";
    }

    @RequestMapping("update")
    public String update(Teacher s, ModelMap modelMap) {
        try{
            teacherService.update(s);
        }
        catch(Exception e){
            modelMap.put("error", e);
            return "error";
        }
        return "redirect:/teacher/list";
    }
    @RequestMapping("search")
    public String search(Teacher s, ModelMap modelMap) {
        modelMap.put("teacherList", teacherService.search(s));
        return "teacher/list";
    }
}
